package com.xiaomaoguai.meizitu;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @Description :
 * @FileName: ParserMeizi.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年6月25日 下午10:50:46
 * @Version:V1.00
 */
public class ParserMeizi extends AbstractHttpUtils {

	private static final String URL = "http://www.meizitu.com/";
	private static String SAVE_PATH = "D://meizitu5/";
	private static long num = 0L;
	private final static ExecutorService es = Executors.newFixedThreadPool(10);
	private final static String CONNECTION = "keep-alive";
	private final static String USER_AGENT = "Mozilla/5.0";

	private static HttpClientContext context = null;

	public static void main(String[] args) throws IOException {
		ParserMeizi parserMeizi = new ParserMeizi();
		parserMeizi.doGetWithCookie(URL);

		Connection con = Jsoup.connect(URL);
		con.header(HttpHeaders.CONNECTION, CONNECTION);
		con.header(HttpHeaders.USER_AGENT, USER_AGENT);
		con.cookies(parserMeizi.cookieMap);

		context = parserMeizi.setContext();

		Document doc = con.get();
		if (doc != null) {
			System.out.println("##主目录解析开始##");
			parserTagURL(doc);
		}
	}

	public static void parserTagURL(Document doc) throws IOException {
		Element tagElement = doc.getElementById("subcontent clearfix");
		if (tagElement != null) {
			Elements spanElements = tagElement.getElementsByTag("span");
			Elements aElements = spanElements.get(0).getElementsByTag("a");
			for (int i = 1; i < aElements.size(); i++) {
				// 进入分类
				String href = aElements.get(i).attr("href");
				System.out.println(href);
				getTagPagePicURL(href);
			}
		}
	}

	public static void getTagPagePicURL(String href) throws IOException {
		Connection conn = getConnection(href);
		Document document = conn.get();
		Elements listPic = document.getElementsByClass("wp-list");
		Elements elements = listPic.get(0).getElementsByTag("a");
		for (Element element : elements) {
			String attr = element.attr("href");
			getSecondPagePicURL(attr);
		}
	}

	public static void getSecondPagePicURL(String href) throws IOException {
		Connection conn = getConnection(href);
		Document document = conn.get();
		Element idElement = document.getElementById("picture");
		Elements imgElements = idElement.getElementsByTag("img");
		for (Element element : imgElements) {
			String attr = element.attr("src");
			System.out.println("图片地址：" + attr);
			doTask(attr, ".jpg");
		}
	}

	public static void doTask(String httpUrl, String suffix) {
		es.execute(new Runner(httpUrl, suffix));
	}

	public static void downImg(String httpUrl, String suffix) throws ClientProtocolException, IOException {
		HttpGet httpGet = new HttpGet(httpUrl);
		httpGet.setHeader(HttpHeaders.USER_AGENT, USER_AGENT);
		ParserMeizi parserMeizi = new ParserMeizi();
		HttpResponse response = parserMeizi.defaultHttpClient.execute(httpGet, context);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) {
			httpGet.abort();
			throw new RuntimeException("HttpClient,error status code :" + statusCode);
		}
		HttpEntity entity = response.getEntity();
		InputStream inputStream = entity.getContent();
		File file = new File(SAVE_PATH + (num++) + suffix);
		FileUtils.copyInputStreamToFile(inputStream, file);
	}

	private static class Runner implements Runnable {

		private String url;

		private String fileName;

		public Runner(String url, String fileName) {
			super();
			this.url = url;
			this.fileName = fileName;
		}

		public void run() {
			try {
				downImg(url, fileName);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static Connection getConnection(String url) {
		Connection con = Jsoup.connect(url);
		con.header(HttpHeaders.CONNECTION, CONNECTION);
		con.header(HttpHeaders.USER_AGENT, USER_AGENT);
		return con;
	}
}